<?php

namespace App\Http\Controllers\Api\Scenic;

use App\Http\Controllers\Controller;
use App\Models\Scenic\ScenicSpotGoodsProvider;
use App\Models\Scenic\ScenicSpotProvider;
use App\Services\Scenic\Adapter;
use App\Services\Scenic\Query\ScenicQueryFactoryInterface;
use App\Services\Scenic\ScenicQueryFactory;
use App\Trip\Enums\Scenic\ScenicProvider;
use Illuminate\Http\Request;

class ScenicTicketController extends Controller
{

    private ScenicQueryFactoryInterface $scenicQuery;

    public function __construct(
        Request $request
    )
    {
        $providerValue = $request->input('provider',ScenicProvider::TUNIU->value);
        $provider = (ScenicProvider::from($providerValue));
        $this->scenicQuery = (new ScenicQueryFactory())->findOneByProvider($provider);
    }

    /**
     * 门票列表
     * @param Request $request
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\Response
     */
    public function tickets(Request $request)
    {
        $id = $request->input('scenic_id');
        if (empty($id)) {
            return $this->error(404, '参数错误');
        }

        $spotProvider = ScenicSpotProvider::where('scenic_id',$id)->first();
        if ($spotProvider instanceof ScenicSpotProvider){
            $provider = (ScenicProvider::from($spotProvider->provider));
            $this->scenicQuery = (new ScenicQueryFactory())->findOneByProvider($provider);
            $providerScenicId = $spotProvider->provider_scenic_id;
        }else{
            $providerScenicId = $id;
        }

        try {
            $data = $this->scenicQuery->tickets($id,$providerScenicId);
        }catch (\Exception $exception){
            return $this->error(404,$exception->getMessage());
        }

        return $this->success('success', ['tickets' => $data]);
    }

    /**
     * 门票详情
     * @param Request $request
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\Response
     */
    public function ticket(Request $request)
    {
        $ticketId = $request->input('ticket_id');
        $scenicId = $request->input('scenic_id');
        $spotProvider = ScenicSpotGoodsProvider::where('scenic_id',$scenicId)
            ->where('ticket_id',$ticketId)
            ->first();
        if ($spotProvider instanceof ScenicSpotGoodsProvider){
            $provider = (ScenicProvider::from($spotProvider->provider));
            $this->scenicQuery = (new ScenicQueryFactory())->findOneByProvider($provider);
            $providerTicketId = $spotProvider->provider_ticket_id;
        }else{
            $providerTicketId = $ticketId;
        }

        try {
            $data = $this->scenicQuery->ticket($providerTicketId);
        }catch (\Exception $exception){
            return $this->error(404,$exception->getMessage());
        }

        return $this->success('success', $data);
    }


}
